#include<iostream>
#include<pthread.h>
#include<unistd.h>
using namespace std;

pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

int tickets = 10000;

void* ThreadRoutine(void* arg)
{
    string name =static_cast<const char*>(arg);

    while(true)
    {
        //sleep(1);
        usleep(1000);
        pthread_mutex_lock(&mutex);
        if(tickets >0)
        {
            cout<<name<<" tickets: "<<tickets--<<endl;
        }
        else
        {
            cout<<name<<"without tickets!"<<endl;
            pthread_cond_wait(&cond,&mutex);
        }
        pthread_mutex_unlock(&mutex);
        // pthread_mutex_lock(&mutex);
        // pthread_cond_wait(&cond,&mutex);   //遇到条件变量进入等待
        // cout<<name<<endl;
        // pthread_mutex_unlock(&mutex);
    }
}

int main()
{
    pthread_t t1,t2,t3;
    pthread_create(&t1,nullptr,ThreadRoutine,(void*)"Thread-1");
    pthread_create(&t2,nullptr,ThreadRoutine,(void*)"Thread-2");
    pthread_create(&t3,nullptr,ThreadRoutine,(void*)"Thread-3");

    sleep(3);

    while(true)
    {
        sleep(10);

        pthread_mutex_lock(&mutex);
        tickets+=1000;
        pthread_mutex_unlock(&mutex);

        //pthread_cond_signal(&cond);
        pthread_cond_broadcast(&cond);
    }


    // while(true)
    // {
    //     //pthread_cond_broadcast(&cond);  //一次性全部唤醒
    //     pthread_cond_signal(&cond);     //按照条件变量队列一个一个唤醒
    //     sleep(1);
    // }

    pthread_join(t1,nullptr);
    pthread_join(t2,nullptr);
    pthread_join(t3,nullptr);
}